using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace ChuanPlus.FormControl
{
    public partial class ControlNewRequest : DevExpress.XtraEditors.XtraUserControl
    {
        DataTable m_dtRequestProduct = new DataTable();
        public ControlNewRequest()
        {
            InitializeComponent();
            comboApproved.Properties.Items.AddRange(xpColUsers);
            m_dtRequestProduct.Columns.Add(new DataColumn("ItemCode"));
            m_dtRequestProduct.Columns.Add(new DataColumn("Description"));
            m_dtRequestProduct.Columns.Add(new DataColumn("ID"));
            m_dtRequestProduct.Columns.Add(new DataColumn("Unit"));
            m_dtRequestProduct.Columns.Add(new DataColumn("Quantity"));
            m_dtRequestProduct.Columns.Add(new DataColumn("AvaiQty"));
            m_dtRequestProduct.Columns.Add(new DataColumn("TakeBy"));
            m_dtRequestProduct.Columns.Add(new DataColumn("Note"));
            grid.DataSource = m_dtRequestProduct;
            xpColProducts.AddRange(ChuanPlus.DAO.StockDAO.ListProductByWarehouseName("Stock"));
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if(e.Column.FieldName == "Description")
            {
                Product pro = repoItemLookUpProduct.GetDataSourceRowByKeyValue(e.Value) as Product;
                if (pro != null)
                {
                    DataRow row = gridView1.GetFocusedDataRow();
                    row["ItemCode"] = pro.ItemCode;
                    row["Unit"] = pro.Unit;
                    row["Quantity"] = 0;
                    row["ID"] = pro.ID;
                    row["AvaiQty"] = (ChuanPlus.DAO.StockDAO.GetStock(pro.ID,2)).QtyBalance;
                }                
            }
                
        }


        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                gridView1.DeleteRow(gridView1.FocusedRowHandle);
            }
        }
        #region validation
        private bool FormValidation()
        {
            if (textRequestTo.Text.Trim() == "")
            {
                MessageBox.Show("Please enter request to field", "Message");
                textRequestTo.Focus();
                return false;
            }
            if (textRequestID.Text.Trim() == "")
            {
                MessageBox.Show("Please enter request ID", "Message");
                textRequestID.Focus();
                return false;
            }
            if (dateRequest.Text.Trim() == "")
            {
                MessageBox.Show("Please select request date", "Message");
                dateRequest.Focus();
                return false;
            }
            if (comboApproved.Text == "")
            {
                MessageBox.Show("Please select approve person", "Message");
                comboApproved.Focus();
                return false;
            }
            if (m_dtRequestProduct.Rows.Count <= 0)
            {
                MessageBox.Show("Please select product to request", "Message");
                grid.Focus();
                return false;
            }
            int DSIndex = ValidatingQuantity();
            if (DSIndex != -1)
            {
                gridView1.FocusedRowHandle = gridView1.GetRowHandle(DSIndex);
                return false;
            }
            DSIndex = validateTakeStaff();
            if (DSIndex != -1)
            {
                gridView1.FocusedRowHandle = gridView1.GetRowHandle(DSIndex);
                return false;
            }
            return true;
        }
        private void comboApproved_Validating(object sender, CancelEventArgs e)
        {
            Users u = comboApproved.SelectedItem as Users;
            if (u == null)
            {
                e.Cancel = true;
                comboApproved.ErrorText = "Staff " + comboApproved.Text + " does not exsit";
            }
        }
        /// <summary>
        /// validate quantity to request
        /// </summary>
        /// <returns></returns>
        private int ValidatingQuantity()
        {

            for (int i = 0; i < m_dtRequestProduct.Rows.Count; i++)
            {
                Object qty = m_dtRequestProduct.Rows[i]["Quantity"];
                if (qty == DBNull.Value || Convert.ToDouble(qty) <= 0)
                {
                    MessageBox.Show("Please enter quantity", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return i;
                }
            }
            return -1;
        }
        /// <summary>
        /// validate TakenBy staff
        /// </summary>
        private int validateTakeStaff()
        {
            for (int i = 0; i < m_dtRequestProduct.Rows.Count; i++)
            {
                Object staff = m_dtRequestProduct.Rows[i]["TakeBy"];
                if (staff == DBNull.Value)
                {
                    MessageBox.Show("Please enter staff will taken product", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return i;
                }
            }
            return -1;
        }
        private void gridView1_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            if (gridView1.FocusedColumn.FieldName == "Quantity")
            {
                DataRow row = gridView1.GetFocusedDataRow();
                if (Convert.ToDouble(e.Value) > Convert.ToDouble(row["AvaiQty"]))
                {
                    e.Valid = false;
                    e.ErrorText = "Maximum is " + row["AvaiQty"].ToString();
                }
            }
        }
        #endregion
        private void buttonSubmit_Click(object sender, EventArgs e)
        {
            if (!FormValidation()) return;
             DialogResult result =  MessageBox.Show("Are you sure want to create a new Request?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
             if (result.ToString() == "Yes")
             {
                 // get summary value from footer row
                 double total = Convert.ToDouble(gridView1.Columns["Quantity"].SummaryItem.SummaryValue);
                 Requesting req  = new Requesting(textRequestID.Text,textRequestTo.Text,dateRequest.DateTime,comboApproved.SelectedItem as Users,total,"H");
                 foreach(DataRow item in m_dtRequestProduct.Rows)
                 {
                    Stock s = ChuanPlus.DAO.StockDAO.GetStock(Convert.ToInt32(item["ID"]),2);
                     Users u = ChuanPlus.DAO.UserDAO.getUserById(Convert.ToInt32(item["TakeBy"]));
                 	RequestingDetails details = new RequestingDetails(req,s,Convert.ToDouble(item["Quantity"]),item["Unit"].ToString(),u,item["Note"].ToString());
                     req.RequestingDetails.Add(details);
                 }
                 req.Save();
                 Reset();                        
             }
        }

        private void buttonReset_Click(object sender, EventArgs e)
        {
            Reset();
        }
        private void Reset()
        {
            textRequestTo.Text = textRequestID.Text = comboApproved.Text = dateRequest.Text = "";
            m_dtRequestProduct.Clear();
            
        }

      
        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            if (gridView1.GetFocusedRowCellValue("Description") == DBNull.Value)
            {
                int DSIndex = gridView1.GetDataSourceRowIndex(gridView1.FocusedRowHandle);
                m_dtRequestProduct.Rows.RemoveAt(DSIndex);
            }
        }

        
    }
}
